package com.kili.file.service.impl;

import com.kili.file.config.systemparam.FileUploadLocalParamConfig;
import com.kili.file.controller.request.FileUploadRequest;
import com.kili.file.exception.FileUploadException;
import com.kili.file.service.FileUploadService;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import static com.kili.file.common.IConstants.LOCAL_STORAGE_MAPPING_PATH;
import static com.kili.file.common.IConstants.SLASH;

/**
 * LocalStorage
 *
 * @author Gordon
 * @version 2019/3/28
 */
@Slf4j
@Setter
public class FileUploadWithLocalStorage implements FileUploadService {


    private FileUploadLocalParamConfig paramConfig;

    @Override
    public String uploadHandler(FileUploadRequest request) {
        String fileName = request.getFile().getOriginalFilename();
        MultipartFile file = request.getFile();
        log.info("Original file name is {} content type is {}", fileName, file.getContentType());

        String path = request.getUrl();

        Path destFilePath = Paths.get(paramConfig.getPath() + path);
        //Valid whether file has been existed ?
        if (Files.exists(destFilePath)) {
            log.warn("Current path has been existed the duplicate file - path {} file {} ",
                    paramConfig.getPath(),
                    fileName);
            throw new FileUploadException("Current path has been existed " + destFilePath.toString());
        }

        String url = new StringBuilder(paramConfig.getHost())
                .append(LOCAL_STORAGE_MAPPING_PATH)
                .append(SLASH)
                .append(path)
                .toString();

        log.debug("Target file path is  {} file target name is {}", destFilePath, fileName);

        try {
            file.transferTo(destFilePath);
            destFilePath.toFile().setReadOnly();
            log.info("Local upload successful - url : {}", url);
        } catch (Exception ex) {
            log.error("Local Storage file error - path : {} file : {}", destFilePath.toString(), fileName, ex);
            throw new FileUploadException("upload error");
        }
        return url;
    }


}
